from fastapi import APIRouter, Depends, HTTPException, status

from app.dependencies_simple import get_auth_service, get_current_user
from app.models.schemas import APIResponse, UserCreate, UserLogin, UserInfo
from app.services.simple_json_auth_service import SimpleJSONAuthService

router = APIRouter(tags=["简化认证"])

@router.post("/register", response_model=APIResponse[UserInfo])
def register(
    user_data: UserCreate,
    auth_service: SimpleJSONAuthService = Depends(get_auth_service)
):
    """用户注册 - 简化版本"""
    try:
        user_info = auth_service.register(user_data)
        return APIResponse(
            message="注册成功",
            data=user_info
        )
    except ValueError as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="注册失败"
        )

@router.post("/login")
def login(
    login_data: UserLogin,
    auth_service: SimpleJSONAuthService = Depends(get_auth_service)
):
    """用户登录 - 简化版本"""
    try:
        result = auth_service.login(login_data)
        if not result:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="用户名或密码错误"
            )
        
        return APIResponse(
            message="登录成功",
            data=result
        )
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="登录失败"
        )

@router.get("/me")
def get_current_user_info(
    current_user: dict = Depends(get_current_user)
):
    """获取当前用户信息"""
    try:
        user_info = {
            "id": current_user['id'],
            "username": current_user['username'],
            "email": current_user['email'],
            "role": current_user.get('role', 'user'),
            "is_active": current_user.get('is_active', True),
            "created_at": current_user.get('created_at'),
            "last_login": current_user.get('last_login')
        }
        
        return APIResponse(
            message="获取用户信息成功",
            data=user_info
        )
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取用户信息失败"
        )

@router.post("/logout")
def logout(
    current_user: dict = Depends(get_current_user),
    auth_service: SimpleJSONAuthService = Depends(get_auth_service)
):
    """用户登出"""
    try:
        success = auth_service.logout(current_user['id'])
        return APIResponse(
            message="登出成功" if success else "登出失败",
            data={"success": success}
        )
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="登出失败"
        )
